#include "CCRC32.h"
#include <stdio.h>

CCRC32* CCRC32::m_pInstance = NULL;

void CCRC32::initCRC32Table()
{
	// This is the official polynomial used by CRC-32 in PKZip, WinZip and Ethernet. 
	unsigned int ulPolynomial = 0x04c11db7;
	unsigned int crc;
	// 256 values representing ASCII character codes.
	for (size_t i = 0; i <= 0xFF; i++)
	{
		crc = i;
		for (size_t j = 0; j < 8; j++)
		{
			if (crc & 1)
			{
				crc = (crc >> 1) ^ ulPolynomial;
			}
			else {
				crc >>= 1;
			}
		}
		m_szCRC32Table[i] = crc;
	}
}

//用m_szCRC32Table寻找表来产生数据的CRC值
uint64_t CCRC32::getCRC(unsigned char* buffer, unsigned int dwSize)
{
	uint64_t  crc(0xffffffff);

	for (size_t i = 0; i < dwSize; i++)
	{
		crc = (crc >> 8) ^ m_szCRC32Table[((unsigned char)(crc & 0xff) ^ buffer[i])];
	}

	return crc ^ 0xffffffff;
}

CCRC32::CCRC32()
{
	initCRC32Table();
}
